import { Equip } from '@libs/db/models/equip.model';
import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';
import { ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';

class equipPostDto {
  @ApiProperty({ description: '装备名册' })
  name: string;
  @ApiProperty({ description: '装备图标' })
  icon: string;
  @ApiProperty({ description: '装备描述' })
  content: string;
}

@ApiTags('装备接口')
@Controller('equips')
export class EquipsController {
  constructor(@InjectModel(Equip) private readonly EquipModel: ModelType<Equip>) {}

  @Get('page/')
  @ApiOperation({summary: '装备列表'})
  async selectAll(@Query() pages: any) {
    let { page, pagesize, sort, name = '' } = pages;
    const total = await this.EquipModel.countDocuments({$or: [{'name': {'$regex': name}}]});

    const skip: number = page * pagesize - pagesize;
    pagesize = pagesize - 0;

    const data = await this.EquipModel.find({$or: [{'name': {'$regex': name}}]}).skip(skip).limit(pagesize).sort({_id: sort});

    return {
      status: 200,
      total,
      content: data
    }
  }

  @Get(':id')
  @ApiOperation({summary: '根据id查找装备'})
  async selectId(@Param('id') id: string) {
    try {
      return await this.EquipModel.findById(id);
    } catch(Err) {
      return {
        success: '创建失败' + Err
      }
    }
  }

  @Get('/name/:name')
  @ApiOperation({summary: '根据装备名，查找装备'})
  async selectName(@Param('name') name: string) {
    try {
      return await this.EquipModel.findOne({$or: [{'name': {'$regex': name}}]});
    } catch (Err) {
      return '无数据';
    }
  }

  @Post()
  @ApiOperation({summary: '创建装备'})
  async create(@Body() equipPostDto: equipPostDto) {
    try {
      await this.EquipModel.create(equipPostDto);
      return {
        success: '创建成功'
      }
    } catch(Err) {
      return {
        success: '创建失败' + Err
      }
    }
    
  }

  @Put(':id')
  @ApiOperation({summary: '修改装备'})
  async update(@Param('id') id: string, @Body() equipPostDto: equipPostDto) {
    await this.EquipModel.updateOne({_id: id}, equipPostDto);
    return {
      success: '修改成功'
    }
  }

  @Delete(':id')
  @ApiOperation({summary: '删除装备'})
  async remove(@Param('id') id: string) {
    await this.EquipModel.findOneAndDelete({_id: id});
    return {
      success: '删除成功'
    }
  }
}